﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using CounterServerModel;
using CounterServerModel.Exceptions;
using CounterServerModel.Authentication;

namespace SmartCounters
{
	public partial class Login : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			Session.Clear();
		}

		public void CommitLogin(object sender, EventArgs e)
		{
			System.Threading.Thread.Sleep(500);
			UserInfo loggedInUser = null;
			AuthenticationService authService;
			AuthenticatedUserCredentials authenticatedCredentials = null;

			string userName = txtUserName.Text;
			string password = txtPassword.Text;

			try
			{
				authService = new AuthenticationService();
				authenticatedCredentials = authService.Authenticate(new UserCredentials(userName, password));
			}
			catch (Exception ex)
			{
				lblErrorText.Text = ex.Message ;
				return;
			}

			if (authenticatedCredentials != null)
			{
				loggedInUser = getUserDetails(authenticatedCredentials);
				Session.Add(MainTemplate.k_CurrentAuthenticatedUserSessionKey, authenticatedCredentials);
				Session.Add(MainTemplate.k_CurrentLoggedInUserSessionKey, loggedInUser);
				Response.Redirect("~/MainMenu.aspx");
			}
			else
			{
				lblErrorText.Text = "Username or Password are incorrect.";
			}

		}

		private static UserInfo getUserDetails(AuthenticatedUserCredentials i_AuthenticatedCredentials)
		{
			UserInfo loggedInUser;
			InformationReader informationReader = new InformationReader();

			loggedInUser = informationReader.GetUserInformation(i_AuthenticatedCredentials, i_AuthenticatedCredentials.ID);
			return loggedInUser;
		}

	}
}